package com.boe.common.util;

import lombok.*;
import com.boe.common.base.IScopeData;
import com.boe.common.base.ScopeStack;
import lombok.SneakyThrows;

import java.io.Flushable;
import java.util.function.Supplier;

public class ScopeUtil {

    private static ThreadLocal<ScopeStack> scopes = ThreadLocal.withInitial(() -> {
        return new ScopeStack();
    });

    public static ScopeStack getScopes() {
        return scopes.get();
    }


@SneakyThrows
    public static <T> T usingScope(IScopeData scopeData, Supplier<T>  body  )  {

        getScopes().push(scopeData);


        try {
            var ret = body.get();

            //自动释放
                if (scopeData instanceof Flushable) {
                    ((Flushable) scopeData).flush();
                }
                if (scopeData instanceof AutoCloseable) {
                    ((AutoCloseable) scopeData).close();
                }
            return ret;
        } finally {
            //自动释放
            getScopes().pop();
        }
    }

}
